package org.game.module.datingbo.handler;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.common.collect.Lists;
import com.xiaoleilu.hutool.util.RandomUtil;
import org.cfg.DatingCfg;
import org.cfg.DatingRuleCfg;
import org.cfg.RoleCfg;
import org.cfg.cache.DatingRuleCfgCache;
import org.constant.DatingConstant;
import org.constant.ItemConstantId;
import org.error.GameErrorCode;
import org.game.constant.DatingTypeConstant;
import org.game.db.bean.CurrentScriptRecord;
import org.game.db.bean.Dating;
import org.game.db.bean.Player;
import org.game.db.bean.Role;
import org.game.db.cache.RoleCache;
import org.game.log.LogDating;
import org.game.log.builder.LogDsp;
import org.game.log.dsp.DatingDsp;
import org.game.log.dsp.GoodsDsp;
import org.game.manager.ItemManager;
import org.game.module.datingbo.DatingBO;
import org.game.module.datingbo.DatingType;
import org.game.msgBuilder.DatingMsgBuilder;
import org.game.protobuf.c2s.C2SDatingMsg;
import org.game.protobuf.s2c.S2CItemMsg;
import org.game.util.ProtoUnit;
import org.utils.CommonUtil;

import com.sojoys.artifact.tools.ToolError;

/**
 * Created by fxf on 2017/11/20.
 */
@DatingType(DatingTypeConstant.DATING_TYPE_DAILY)
public class DailyDatingHandler extends AbstractDatingHandler {

    @Override
    public byte[] getScript(Player player, C2SDatingMsg.GetScriptMsg msg) {
        ToolError.isAndTrue(GameErrorCode.DAILY_DATING_COUNT_IS_ZERO, "日常约会次数已经用完", player.getPlayerProxy().getGoodsNumByCid(ItemConstantId.DAILY_DATING_COUNT) <= 0);
        int buildingId = msg.getBuildId();
        int roleId = msg.getRoleId();
        Role role = RoleCache.me().getByCidPlayerId(roleId,player.getId());
        ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR, "获取剧本，roleId错误，role == null",role == null);

        RoleCfg roleCfg = role.getRoleProxy().getConfig();
        LogDsp log = LogDsp.newBuilder(GoodsDsp.USE_DAILY_DATING_COUNT).addAttr("roleId", roleCfg.getId()).addAttr("buildingId", buildingId);
        
        ItemManager.costGoodsByCid(player, CommonUtil.packageMap(ItemConstantId.DAILY_DATING_COUNT,1), log, S2CItemMsg.ItemList.newBuilder());

        // 获取剧本id
        int datingRuleCid = getDatingRuleId(role, buildingId, getTimeQuantum());
        ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR, datingRuleCid == 0);

        // 筛选分支节点
        Map<Integer, List<Integer>> branchNodes = getScriptBranchNode(player, datingRuleCid,msg);

        // 获取开始节点
        int startNodeId = getStartNodeId(datingRuleCid);

        createCurrentScriptRecord(player, datingRuleCid, branchNodes, startNodeId, Arrays.asList(roleId));

        LogDating.me().log(player.getId(),getDatingType(),datingRuleCid,roleCfg.getId(), LogDsp.newBuilder(DatingDsp.GET_SCRIPT));

        player.getPlayerProxy().sendMsg(DatingBO.sendEveryDayScript,DatingMsgBuilder.getDatingScriptMsg(datingRuleCid,branchNodes));
        return new byte[0];
    }


    @Override
    protected void endDatingRecord(Player player, Dating dating, DatingCfg cfg, int roleCid, CurrentScriptRecord record) {
        super.endDatingRecord(player,dating,cfg,roleCid,record);
    }


    /**
     * 根据区域id获取剧本id
     * @param buildingCid 区域id
     * @return
     */
    public Integer getDatingRuleId(Role role, int buildingCid, int timeFrame){
        List<DatingRuleCfg> allCfgList = DatingRuleCfgCache.me().getDatingRuleByRoleIdDatingType(role.getCid(),getDatingType());
        List<DatingRuleCfg> tempList = Lists.newArrayList();
        AtomicInteger maxWeight = new AtomicInteger();

        allCfgList.forEach(ruleCfg -> {
            //条件1：建筑id
            Integer condition = ruleCfg.getEnterCondtionByType(DatingConstant.ENTER_CDTION_KEY_BUILD_CID);
            if (condition !=0 && condition != buildingCid)
                return;

            //条件2：好感度
            condition = ruleCfg.getEnterCondtionByType(DatingConstant.ENTER_CDTION_KEY_FAVOR);
            if (condition > role.getFavor())
                return;

            maxWeight.addAndGet(ruleCfg.getEnterCondtionByType(DatingConstant.ENTER_CDTION_KEY_WEIGHT));
            tempList.add(ruleCfg);
        });
        int max = maxWeight.get();
        if(max > 0){
            int randomWeight = RandomUtil.randomInt(max);
            int weight = 0;
            for (DatingRuleCfg ruleCfg : tempList) {
                weight += ruleCfg.getEnterCondtionByType(DatingConstant.ENTER_CDTION_KEY_WEIGHT);
                if(randomWeight <= weight)
                    return ruleCfg.getId();
            }
        }
        return 0;
    }

}
